<template>
  <el-row class="tool-bar">
    <tool-bar-item
      v-for="(item, index) in toolBarItems"
      :label="item.label"
      :selected="index === selected"
      :isLast="index === toolBarItems.length - 1"
      :key="index"
      @click="handleToolItemClick(index, index === toolBarItems.length - 1)"
    >
      <template #icon>
        <el-icon>
          <component :is="item.icon"></component>
        </el-icon>
      </template>
    </tool-bar-item>
    <el-select
      size="small"
      style="margin-left: 5px;"
      placeholder="选择类型"
      v-model="type"
      @change="handleChange"
    >
      <el-option
        v-for="(item, index) in typeData"
        :key="index"
        :value="item.typeId"
        :label="item.name"
      ></el-option>
    </el-select>
  </el-row>
</template>

<script>
import ToolBarItemVue from "./ToolBarItem.vue";

import { typeAll } from "@/api/type";

export default {
  components: {
    ToolBarItem: ToolBarItemVue,
  },
  data() {
    return {
      toolBarItems: [
        {
          label: "综合",
          icon: "CaretBottom",
          orderBy: 0,
        },
        {
          label: "销量",
          icon: "CaretBottom",
          orderBy: 1,
        },
        {
          label: "评论数",
          icon: "CaretBottom",
          orderBy: 2,
        },
        // {
        //   label: "新品",
        //   icon: "CaretBottom",
        //   orderBy: 4
        // },
        {
          label: "价格",
          icon: "DCaret",
          change: 0,
          orderBy: 5,
        },
      ],
      selected: 0,
      orderByColumn: 0,
      type: 0,
      typeData: [],
    };
  },
  methods: {
    doTypeAll() {
      typeAll(0, 1000).then((res) => {
        this.typeData = [{typeId: 0, name: "全部"}, ...res.list];
      });
    },
    handleToolItemClick(index, isChange) {
      this.selected = index;
      if (isChange) {
        switch (this.toolBarItems[index].change) {
          case 0:
            this.toolBarItems[index].icon = "CaretBottom";
            break;
          case 1:
            this.toolBarItems[index].icon = "CaretTop";
            break;
        }

        this.toolBarItems[index].change =
          (this.toolBarItems[index].change + 1) % 2;
        this.orderByColumn =
          this.toolBarItems[index].change + this.toolBarItems[index].orderBy;
      } else {
        this.toolBarItems[this.toolBarItems.length - 1].icon = "DCaret";
        this.orderByColumn = this.toolBarItems[index].orderBy;
      }

      this.$emit("changeOrderBy", this.orderByColumn);
    },
    handleChange(val) {
      this.$emit("changeType", val);
    }
  },
  created() {
    this.doTypeAll();
    if (this.$route.query.type != undefined) {
      this.type = parseInt(this.$route.query.type);
    }
  },
};
</script>

<style scoped>
.tool-bar {
  background-color: #f1f1f1;
  margin: 10px auto;
  padding: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>